package com.woniuxy.reader.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.reader.entity.Book;
import com.woniuxy.reader.entity.Chapter;
import com.woniuxy.reader.mapper.AuthorMapper;
import com.woniuxy.reader.mapper.BookMapper;
import com.woniuxy.reader.mapper.ChapterMapper;
import com.woniuxy.reader.service.ChapterService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zh_o
 * @since 2020-10-12
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

    @Resource
    private ChapterMapper chapterMapper;

    @Resource
    private AuthorMapper authorMapper;

    @Resource
    private BookMapper bookMapper;

    /**
     * 获取章节页面初始化信息
     * @param chapterId 章节id
     * @return
     */
    @Override
    public Chapter getChapterInfo(Integer chapterId) {
        // 获取章节数据
        Chapter chapter = chapterMapper.selectById(chapterId);
        // 获取书籍信息
        Book book = bookMapper.selectById(chapter.getBookId());
        chapter.setBookName(book.getBookName());
        chapter.setDescription(book.getDescription());
        // 获取作者信息
        chapter.setAuthorName(authorMapper.selectById(book.getAuthorId()).getPenName());
        // 获取第一章id
        List<Chapter> minList = chapterMapper.selectPage(new Page<>(0, 1), new QueryWrapper<Chapter>().eq(Chapter.BOOK_ID, book.getBookId()).orderByAsc(Chapter.UPDATE_TIME)).getRecords();
        chapter.setMinId(minList.get(0).getChapterId());
        // 获取最后一章id
        List<Chapter> maxList = chapterMapper.selectPage(new Page<>(0, 1), new QueryWrapper<Chapter>().eq(Chapter.BOOK_ID, book.getBookId()).orderByDesc(Chapter.UPDATE_TIME)).getRecords();
        chapter.setMaxId(maxList.get(0).getChapterId());
        return chapter;
    }
}
